﻿#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System.Collections.Generic;
using NUnitGrid.Server.Plugins.Clients.Client;


namespace NUnitGrid.Server.Plugins.Nodes
{
    public class PendingRunOnGridTasksCollection
    {
        private readonly Dictionary<RunOnGridTask, IClientProxy> clientMap =
            new Dictionary<RunOnGridTask, IClientProxy>();

        private readonly List<RunOnGridTask> taskQueue = new List<RunOnGridTask>();

        public int Count
        {
            get { return taskQueue.Count; }
        }

        public RunOnGridTask this[int index]
        {
            get { return taskQueue[index]; }
        }

        public RunOnGridTask[] this[IClientProxy client]
        {
            get { return GetTasksForClient(client); }
        }

        public void Add(IClientProxy client, RunOnGridTask task)
        {
            taskQueue.Add(task);
            clientMap.Add(task, client);
        }

        public void Remove(RunOnGridTask task)
        {
            taskQueue.Remove(task);
            clientMap.Remove(task);
        }

        public void RemoveAt(int index)
        {
            var task = taskQueue[index];
            taskQueue.RemoveAt(index);
            clientMap.Remove(task);
        }

        private RunOnGridTask[] GetTasksForClient(IClientProxy client)
        {
            var tasksToStop = new List<RunOnGridTask>();
            foreach (var pendingTask in taskQueue)
            {
                if (clientMap[pendingTask] == client)
                {
                    tasksToStop.Add(pendingTask);
                }
            }
            return tasksToStop.ToArray();
        }
    }
}